package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import com.fsd.admin.model.F_form;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.F_formfield;
import com.fsd.admin.service.F_formfieldService;
import com.fsd.admin.dao.F_formfieldDao;

@Repository("f_formfieldServiceImpl")
public class F_formfieldServiceImpl extends BaseServiceImpl<F_formfield, String> implements F_formfieldService{
    
    private static final Logger log = Logger.getLogger(F_formfieldServiceImpl.class);
    private String depict = "";
    
    @Resource(name = "f_formfieldDaoImpl")
	public void setBaseDao(F_formfieldDao F_formfieldDao) {
		super.setBaseDao(F_formfieldDao);
	}
	
	@Resource(name = "f_formfieldDaoImpl")
	private F_formfieldDao objectDao;

	private static final String TABLE_PREFIX = "f_tbl_";
    
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
    @Override
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
        c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.add(Restrictions.eq("deleted", "0"));
		c.addOrder(Order.asc("adddate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("title") != null && !"".equals(objectMap.get("title"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("title") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	@Override
	public void save(F_formfield obj, A_Employee employee) throws Exception{
        if(obj.getId() != null && !"".equals(obj.getId())){
            //修改
            F_formfield old_obj = objectDao.get(obj.getId());
            

            objectDao.update(old_obj);
        }else{
            //添加
			//设置主键
            obj.setId(this.getUUID());

			objectDao.save(obj);
        }
    }
    
    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	@Override
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		String hql = "";
		objectDao.executeHql("update F_formfield t set t.deleted = '1', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	@Override
	public F_formfield getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		F_formfield obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}

	/**
	 * 创建表单对应的数据库表，并且保存表单字段
	 * @param form
	 * @param list
	 * @return
	 * @throws Exception
	 */
	@Override
	public void saveFormField(F_form form, List<Map<String, Object>> list) throws Exception{
		if(list == null || list.size() == 0) {
			throw new BusinessException("表单数据不能为空");
		}
		//获得表单对应的数据库表名称
		String tableName = getTableName(form);
		List<F_formfield> formfields = new ArrayList<>();
		// 遍历字段list
		for (Map<String, Object> fieldInfo : list) {
			boolean con = true;
			for (F_formfield formfield : formfields) {
				if(fieldInfo.get("fieldname").toString().equals(formfield.getF_name())){
					con = false;
				}
			}
			if(con){
				F_formfield formField = new F_formfield();
				formField.setF_tablename(tableName);
				formField.setF_formid(form.getId());

				formField.setF_name(fieldInfo.get("fieldname").toString());
				formField.setF_title(fieldInfo.get("title").toString());
				formField.setF_plugins(fieldInfo.get("plugins").toString());

				if(fieldInfo.get("fieldflow") != null){
					formField.setF_flow(fieldInfo.get("fieldflow").toString());
				}
				if(fieldInfo.get("orgtype") != null){
					formField.setF_type(fieldInfo.get("orgtype").toString());
				}
				formfields.add(formField);
			}
		}
		//设置表单字段数量
		form.setF_fieldnum(new Long(formfields.size()));

		//如果表存在，就将表删除
		String dropSql = "drop table if exists " + tableName + ";";
		objectDao.executeSql(dropSql);

		//删除表单字段表保存的字段
		String delSql = "delete from f_formfield where f_formId = ?";
		objectDao.executeSql(delSql, form.getId());

		String sql = "select f_name from f_formfield where f_formId = ?";
		List<String> fieldNames = objectDao.queryBySql(sql, form.getId());

		StringBuilder createTableSql = new StringBuilder();
		createTableSql.append("create table ").append(tableName).append(" (");
		createTableSql.append("id varchar(32) not null,");
		for(F_formfield field : formfields) {
			createTableSql.append(field.getF_name());
			createTableSql.append(" ").append(fieldSQL(field)).append(",");
		}
		createTableSql.append("f_formid varchar(32) NOT NULL,");
		createTableSql.append("f_updatetime varchar(14),");
		createTableSql.append("f_orderid varchar(50),");
		createTableSql.append("f_employeeid varchar(32) NOT NULL,");
		createTableSql.append("f_taskid  varchar(50) NOT NULL,");
		createTableSql.append("primary key (id)");
		createTableSql.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
		objectDao.executeSql(createTableSql.toString());

		//将字段保存到字段表
		for (F_formfield formfield : formfields) {
			if(!fieldNames.contains(formfield.getF_name())) {
				formfield.setId(this.getUUID());
				objectDao.save(formfield);
			}
		}
	}

	/**
	 * 获得表名称
	 * @param form
	 * @return
	 */
	private String getTableName(F_form form) {
		return TABLE_PREFIX + form.getF_name();
	}

	/**
	 * 组织表单字段SQL
	 * @param field
	 * @return
	 */
	private String fieldSQL(F_formfield field) {
		String plugins = field.getF_plugins();
		if(plugins.equalsIgnoreCase("textarea") || plugins.equalsIgnoreCase("listctrl")) {
			return " TEXT";
		} else if(plugins.equalsIgnoreCase("text")) {
			String type = field.getF_type();
			if("text".equals(type)) {
				return " VARCHAR(255) DEFAULT ''";
			} else if("int".equals(type)) {
				return " INT DEFAULT 0";
			} else if("float".equals(type)) {
				return " FLOAT ";
			} else {
				return " VARCHAR(255)";
			}
		} else if(plugins.equalsIgnoreCase("radios")) {
			return " VARCHAR(255)";
		} else {
			return " VARCHAR(255)";
		}
	}
}
